package com.qire.manhua.dal.service;

import android.util.Size;

import com.qire.antsbinder.dal.DataService;
import com.qire.antsbinder.dal.annotation.StrategyAnnotation;
import com.qire.antsbinder.dal.annotation.StrategyAnnotation.ThreadMode;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.concurrent.Scheduler;
import com.qire.common.concurrent.ThreadUtil;
import com.qire.common.constant.Url;
import com.qire.common.dal.WarehouseFactory;
import com.qire.common.inject.ViewModelInjector;
import com.qire.common.utils.Logger;
import com.qire.common.utils.ToastHelper;
import com.qire.common.widget.snackbar.Prompt;
import com.qire.manhua.dal.IComicDataDAL;
import com.qire.manhua.dal.IUserDataDAL;
import com.qire.manhua.dal.dao.ComicDatabase;
import com.qire.manhua.dal.dao.ComicChapterDao;
import com.qire.manhua.dal.dao.ComicDownloadDao;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.model.entity.ComicBookEntity.DirectoryInfo;
import com.qire.manhua.model.po.ComicDownloadRecord;
import com.qire.manhua.model.po.LocalComicChapter;
import com.qire.manhua.model.viewModel.impl.ComicDownloadSelectorViewModel;
import com.qire.manhua.model.viewModel.impl.ComicDownloadSelectorViewModel.DownloadSelectorBatchItemViewModel;
import com.qire.manhua.model.viewModel.impl.ComicDownloadSelectorViewModel.DownloadSelectorChapterItemViewModel;
import com.qire.manhua.model.viewModel.impl.ComicDownloadUnlockViewModel;
import com.qire.manhua.model.vo.BatchBuyChaptersPriceVO;
import com.qire.manhua.model.vo.BatchDownloaderInfoVO;
import com.qire.manhua.model.vo.BatchDownloaderInfoVO.ChapterDownloaderInfoVO;
import com.qire.manhua.model.vo.BatchDownloaderInfoVO.ChapterDownloaderInfoVO.ChapterCacheInfoVO;
import com.qire.manhua.model.vo.BatchDownloaderInfoVO.ChapterDownloaderInfoVO.ChapterCacheInfoVO.RectSize;
import com.qire.manhua.model.vo.DirectoryVO;
import com.qire.manhua.model.vo.OkResponseVO;

import java.util.ArrayList;
import java.util.List;

public class ComicDownloadSelectorService extends DataService {

    private final IComicDataDAL comicDataDAL = WarehouseFactory.create(this, IComicDataDAL.class);
    private final IUserDataDAL userDataDAL = WarehouseFactory.create(this, IUserDataDAL.class);

    private final ComicDownloadDao comicDownloadDao = ComicDatabase.database().comicDownloadDao();
    private final ComicChapterDao comicChapterDao = ComicDatabase.database().comicChapterDao();

    private final ComicDownloadSelectorViewModel viewModel;

    public ComicDownloadSelectorService(ComicDownloadSelectorViewModel viewModel) {
        this.viewModel = viewModel;
    }

    /**
     * 同步漫画实体目录信息
     */
    public void syncUpdateComicDirectoryInfo() {
        comicDataDAL.fetchComicDirectoryInfo(viewModel.comicBookId());
    }
    @StrategyAnnotation(event = Url.comicDirectoryInfo, threadMode = ThreadMode.ASYNC)
    public void fetchComicDirectoryInfoApiCallback(DirectoryVO dataVO, boolean isCache) {
        // 未获得数据，可能是api的问题，什么都不处理
        if(ObjectUtil.isNull(dataVO) || ListUtil.isEmpty(dataVO.chapters) || isCache) {
            return;
        }

        // 获得漫画实体对象
        ComicBookEntity comicBookEntity = viewModel.comicBookEntity();

        // 更新填充漫画实体对象数据
        dataVO.updateComicBook(comicBookEntity);

        // 获取本地历史记录
        final List<LocalComicChapter> localComicChapterList = comicChapterDao.queryListBy(viewModel.comicBookId());

        // 保存一份临时的处理数据，以避免脏读脏写导致的 ConcurrentModificationException 问题。
        final ArrayList<DirectoryInfo> directoryInfoList = ListUtil.newArrayList(comicBookEntity.directoryInfoList);

        ThreadUtil.<List<LocalComicChapter>>once().map(localComicChapterList).schedulerBy(Scheduler.Main).andThen(list -> {

            for(DirectoryInfo directoryInfo : directoryInfoList) {
                // 构建单项选项的章节目录，如果存在版权到期需要隐藏，则可能返回null
                DownloadSelectorChapterItemViewModel selectorChapterItem = viewModel.buildSelectorChapterItem(directoryInfo);

                if(ObjectUtil.nonNull(selectorChapterItem)) {
                    // 构建批量选择面板选项，并完成批量选择与单项选择的绑定
                    DownloadSelectorBatchItemViewModel selectorBatchItem = viewModel.buildSelectorBatchItem();
                    selectorBatchItem.addChapterViewModel(selectorChapterItem);

                    // 标记出已存在下载记录的。
                    if(ListUtil.contains(list, value -> value.getId() == directoryInfo.chapterId)) {
                        selectorChapterItem.existDownloaded();
                    }

                    // 默认选中不需要购买的
                    if(directoryInfo.notNeedBuy()) {
                        selectorChapterItem.toggleChoose();
                    }
                }

            }

            viewModel.refreshUI();

        }).accept();

    }

    /**
     * 处理批量解锁章节列表操作
     * 1.获取解锁章节的价格信息
     * 2.批量购买解锁漫画
     * 3.获取批量下载漫画，批量下载
     */
    public void handleBatchUnlockChapterList() {
        viewModel.showLoadDialog();
        comicDataDAL.fetchBatchBuyChaptersPrice(viewModel.comicBookId(), viewModel.needUnlockList());
    }
    @StrategyAnnotation(event = Url.ChapterBuyTotal)
    public void fetchBatchBuyChaptersPriceApiCallBack(BatchBuyChaptersPriceVO dataVO, boolean isCache) {
        viewModel.dismissLoadDialog();

        if (ObjectUtil.isNull(dataVO)) {
            ToastHelper.showToast("数据异常");
            return ;
        }

        ComicDownloadUnlockViewModel unlockViewModel = new ComicDownloadUnlockViewModel();
        unlockViewModel.setBuyPrice(dataVO.discountPrice);
        unlockViewModel.setDiscountInfo(dataVO.total_gold, dataVO.vip_chapter_coin, dataVO.discount / 10f);

        // 显示处理批量解锁的提示对话框
        viewModel.showUnlockPromptDialog(dataVO.singlePrice, unlockViewModel);
    }

    /**
     * 批量购买解锁漫画
     * @param totalPrice 用于后台校验是否金额有改动
     */
    public void batchBuy(float totalPrice) {
        viewModel.showLoadDialog();
        comicDataDAL.batchBuyChapters(viewModel.comicBookId(), viewModel.needUnlockList(), totalPrice);
    }
    @StrategyAnnotation(event = Url.ChapterBuyBatch)
    public void batchBuyChaptersApiCallback(OkResponseVO dataVO, boolean isCache) {
        viewModel.dismissLoadDialog();
        if(ObjectUtil.nonNull(dataVO)) {
            handleComicBatchDownload();
        }
    }

    /**
     * 处理漫画批量下载操作
     * 1.获取批量下载章节的详情
     * 2.保存章节信息到本地数据库
     * 3.刷新保存章节的目录信息到本地数据库
     * 4.开启下载服务下载章节内容图片
     */
    public void handleComicBatchDownload() {
//        if(viewModel.chooseList.isEmpty()){
//            viewModel.startDownloadService();
//            return;
//        }
        viewModel.showLoadDialog();
        comicDataDAL.fetchBatchDownloaderInfo(viewModel.comicBookId(), viewModel.chooseList());
    }
    @StrategyAnnotation(event = Url.ChapterDownBatch, threadMode = ThreadMode.ASYNC)
    public void fetchBatchDownloaderInfoApiCallback(BatchDownloaderInfoVO dataVO, boolean isCache) {

        viewModel.dismissLoadDialog();

        if(ObjectUtil.isNull(dataVO)) {
            return;
        }

        // 检查日常任务完成情况，并提示
        if(dataVO.task_state == 1) {
            ToastHelper.showSnackBar("离线缓存1个章节任务已完成", Prompt.SUCCESS);
        }

        // 开始处理批量下载数据
        if(ListUtil.notEmpty(dataVO.info)) {
            ToastHelper.showToast("正在添加到下载队列");

            // 记录列表,用于保存准备插入数据库的记录(会在下面过滤掉已存在数据的记录)
            ArrayList<LocalComicChapter> recordList = new ArrayList<>();

            for(ChapterDownloaderInfoVO infoVO : dataVO.info) {

                ChapterCacheInfoVO detailInfo = infoVO.detailInfo;

                // 从数据库读取一个章节记录
                LocalComicChapter comicChapter = comicChapterDao.queryBy(detailInfo.id);

                // 如果章节记录不存在则构建一个记录并且插入数据库，如果章节存在则不在记录；
                if(ObjectUtil.isNull(comicChapter)) {
                    comicChapter = new LocalComicChapter();
                    comicChapter.setId(detailInfo.id);
                    comicChapter.setSerialNumber(detailInfo.chapter_px);
                    comicChapter.setComicId(detailInfo.book_id);
                    comicChapter.setComicCover(detailInfo.book_unruly);
                    comicChapter.setComicAuthor(detailInfo.book_author);
                    comicChapter.setComicName(detailInfo.book_name);
                    comicChapter.setChapterName(detailInfo.chapter_name);
                    comicChapter.setContentList(detailInfo.content);

                    ArrayList<Size> sizeList = new ArrayList<>();
                    for (RectSize rectSize : detailInfo.wh) {
                        sizeList.add(new Size(rectSize.w, rectSize.h));
                    }
                    comicChapter.setSizeList(sizeList);

                    comicChapter.setLikeCount(infoVO.tj.like_count);

                    // 保存到列表中之后批量插入数据库
                    recordList.add(comicChapter);
                }
            }

            Logger.d("当前线程-" + Thread.currentThread().getName() + "： 正在写入数据库下载章节记录");
            comicChapterDao.insertReplace(recordList.toArray(new LocalComicChapter[]{}));

            handleComicInfoLocalSave();

            ThreadUtil.<LocalComicChapter[]>once().schedulerBy(Scheduler.Main).andThen(d -> {
                Logger.d("当前线程-" + Thread.currentThread().getName() + "： 写入数据库完毕，启用下载服务开始下载");
                viewModel.startDownloadService();
            }).accept();
        }

    }

    /**
     * 处理漫画相关信息本地保存
     */
    public void handleComicInfoLocalSave() {
        ComicBookEntity comicBookEntity = viewModel.comicBookEntity();

        ComicDownloadRecord comicDownloadRecord = new ComicDownloadRecord();
        comicDownloadRecord.setId(comicBookEntity.id);
        comicDownloadRecord.setComicName(comicBookEntity.bookName);
        comicDownloadRecord.setCover(comicBookEntity.getCoverPlotVertical());

        comicDownloadDao.insertReplace(comicDownloadRecord);
    }

}
